//
//  MQEmoticonCollectionViewCell.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/2/3.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

let EmoticonPageRow = 3
let EmoticonPageCol = 7

class MQEmoticonCollectionViewCell: UICollectionViewCell {
    
    
    lazy var emoticonBtns:[MQEmoticonButton] = [MQEmoticonButton]()
    
    var emoticons:[MQEmoticon]?{
        didSet{
            for emotionBtn in emoticonBtns{
                emotionBtn.hidden = true
            }
            
            for (i, emoticon) in emoticons!.enumerate(){
                
                let btn = emoticonBtns[i]
                btn.emoticon = emoticon
                btn.hidden = false
                if emoticon.type == "0"{
                    //加载表情
                    let imageName = "\(emoticon.path!)/\(emoticon.png!)"
                    btn.setImage(UIImage(named: imageName, inBundle: MQEmoticonTools.shareTools.emoticonBundle, compatibleWithTraitCollection: nil), forState: UIControlState.Normal)
                    btn.setTitle(nil, forState: UIControlState.Normal)
                }else if emoticon.type == "1"{
                    btn.setTitle((emoticon.code! as NSString).emoji(), forState: UIControlState.Normal)
                    btn.setImage(nil, forState: UIControlState.Normal)
                }else{
                    printfLog(emoticon)
                }
            }
        }
    }
    
    var indexPath:NSIndexPath?{
        didSet{
                recentLabel.hidden = (indexPath?.section != 0)
//            indexPathWithLabel.text = "第\(indexPath!.section)组，第\(indexPath!.item)个cell"
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        for _ in 0..<20{
            let btn = MQEmoticonButton()
            btn.addTarget(self, action: "didClickEmoticonBtn:", forControlEvents: UIControlEvents.TouchUpInside)
            btn.titleLabel?.font = UIFont.systemFontOfSize(30)
//            btn.backgroundColor = RandomColor()
            contentView.addSubview(btn)
            emoticonBtns.append(btn)
        }
        contentView.addSubview(deleteBtn)
        contentView.addSubview(recentLabel)
        
        recentLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self.snp_bottom).offset(-5)
        }
        let ges = UILongPressGestureRecognizer(target: self, action: "longPressGesture:")

        addGestureRecognizer(ges)
    }
    
    //监听事件
    
    @objc private func longPressGesture(ges:UIGestureRecognizer){
       let location = ges.locationInView(self)
        for btn in emoticonBtns{
            if CGRectContainsPoint(btn.frame, location){
                
                switch ges.state {
                    case .Began,.Changed:
                        let window = UIApplication.sharedApplication().windows.last
                        window?.addSubview(pressPopView)
                        let rect = btn.superview!.convertRect(btn.frame, toView: window)
                        
                        pressPopView.center.x = btn.center.x
                        pressPopView.frame.origin.y = CGRectGetMaxY(rect) - pressPopView.frame.height
                        pressPopView.setEmoticonBtnImageAndTitle(btn.emoticon!)
                    case .Cancelled, .Ended:
                        pressPopView.removeFromSuperview()
                    default:
                        pressPopView.removeFromSuperview()
                }
//                let popView = MQEmoticonPopView.initPopView()
                
                
            }
        }
    }
    
    //懒加载控件
    private lazy var pressPopView:MQEmoticonPopView = MQEmoticonPopView.initPopView()
    
    private lazy var indexPathWithLabel:UILabel = {
        let label = UILabel()
        label.textAlignment = .Center
        label.font = UIFont.systemFontOfSize(40)
        return label
    }()
    
    private lazy var deleteBtn:UIButton = {
        let btn = UIButton()
        
        btn.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        btn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        return btn
    }()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let btnW = (SCREENW - 10) / CGFloat(EmoticonPageCol)
        let btnH = (self.bounds.size.height-20) / CGFloat(EmoticonPageRow)
        for (i, btn) in emoticonBtns.enumerate(){
            
            let row = i / EmoticonPageCol
            let col = i % EmoticonPageCol
            
            let btnX = CGFloat(col)*btnW + 5
            let btnY = CGFloat(row)*btnH
            
            btn.frame = CGRectMake(btnX, btnY, btnW, btnH)
        }
        deleteBtn.frame = CGRectMake(SCREENW - btnW - 5, 2*btnH, btnW, btnH)
//        printfLog(deleteBtn.frame)
    }
    
    private lazy var recentLabel:UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 15)
        label.text = "最近使用表情"
        return label
    }()
    
    @objc private func didClickEmoticonBtn(btn:MQEmoticonButton){
        
//        let popView = MQEmoticonPopView.initPopView()
        //保存最佳表情
        MQEmoticonTools.shareTools.saveRecentEmoticon(btn.emoticon!)
        
        NSNotificationCenter.defaultCenter().postNotificationName(MQEoticonDidSelectedBtnNotification, object: nil, userInfo: ["emoticon": btn.emoticon!])
        
        let window = UIApplication.sharedApplication().windows.last
        window?.addSubview(pressPopView)
        
        pressPopView.setEmoticonBtnImageAndTitle(btn.emoticon!)
        
        let rect = btn.superview!.convertRect(btn.frame, toView: window)
        pressPopView.center.x = CGRectGetMidX(rect)
        pressPopView.frame.origin.y = CGRectGetMaxY(rect) - pressPopView.frame.size.height
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()){
            self.pressPopView.removeFromSuperview()
        }
    }
    
    @objc private func deleteButtonClick(){
        NSNotificationCenter.defaultCenter().postNotificationName(MQDeleteButtonClickNotification, object: nil)
    }
}
